<template>
    <div class="step2-rule-config">
      <!-- 左侧：规则配置区域 -->
      <div class="config-area">
        <!-- 规则选择器 -->
        <el-card class="mb16">
          <div style="display: flex; align-items: center; gap: 16px;">
            <el-tabs v-model="activeTab" @tab-click="filterRules">
              <el-tab-pane label="全部" name="all" />
              <el-tab-pane label="签到类" name="sign" />
              <el-tab-pane label="分享类" name="share" />
              <el-tab-pane label="购买类" name="buy" />
              <el-tab-pane label="邀请类" name="invite" />
            </el-tabs>
            <el-input
              v-model="search"
              placeholder="搜索规则"
              prefix-icon="el-icon-search"
              style="width: 200px"
              @input="filterRules"
              clearable
            />
          </div>
          <div class="recent-rules" v-if="recentRules.length">
            <span style="color: #888;">最近使用：</span>
            <el-tag
              v-for="rule in recentRules"
              :key="rule.id"
              size="small"
              style="margin-right: 8px; cursor: pointer"
              @click="selectRule(rule)"
            >{{ rule.name }}</el-tag>
          </div>
        </el-card>
  
        <!-- 规则卡片列表 -->
        <div class="rule-list">
          <el-row :gutter="16">
            <el-col :span="8" v-for="rule in filteredRules" :key="rule.id">
              <el-card class="rule-card" shadow="hover">
                <div class="rule-card-header">
                  <span class="rule-name">{{ rule.name }}</span>
                  <el-tag size="small" :type="tagType(rule.type)">{{ rule.typeLabel }}</el-tag>
                </div>
                <div class="rule-desc">{{ rule.desc }}</div>
                <div class="rule-meta">
                  <span>适用：{{ rule.scene }}</span>
                  <el-tag size="small" :type="complexType(rule.complexity)">
                    {{ rule.complexityLabel }}
                  </el-tag>
                </div>
                <el-button size="small" type="primary" @click="openConfig(rule)">选择</el-button>
              </el-card>
            </el-col>
          </el-row>
        </div>
  
        <!-- 已配置规则列表 -->
        <el-card class="mt16">
          <template #header>
            已配置规则
            <span style="color: #888; font-size: 12px;">（可拖拽排序）</span>
          </template>
          <draggable
            v-model="configuredRules"
            item-key="id"
            handle=".drag-handle"
            animation="200"
          >
            <template #item="{ element, index }">
              <div class="configured-rule">
                <span class="drag-handle" style="cursor: grab; margin-right: 8px;">☰</span>
                <span class="rule-name">{{ element.name }}</span>
                <span class="rule-config">{{ element.configSummary }}</span>
                <el-button size="small" type="default" @click="editConfiguredRule(element, index)">编辑</el-button>
                <el-button size="small" type="danger" @click="removeConfiguredRule(index)">删除</el-button>
              </div>
            </template>
          </draggable>
          <div v-if="!configuredRules.length" style="color: #aaa; text-align: center; padding: 16px 0;">
            暂无已配置规则
          </div>
        </el-card>
      </div>
  
      <!-- 右侧：帮助区域 -->
      <div class="help-area">
        <el-tabs>
          <el-tab-pane label="规则模板库">
            <div v-for="tpl in ruleTemplates" :key="tpl.id" class="tpl-item">
              <el-tag>{{ tpl.name }}</el-tag>
              <el-button size="small" type="default" @click="applyTemplate(tpl)">一键应用</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="配置指南">
            <div>1. 选择规则类型，点击"选择"进行参数配置。</div>
            <div>2. 配置完成后可在下方列表编辑、删除、拖拽排序。</div>
          </el-tab-pane>
          <el-tab-pane label="触发逻辑">
            <div>规则触发条件和执行流程将在此展示。</div>
          </el-tab-pane>
          <el-tab-pane label="数据统计">
            <div>展示类似规则的完成率和用户参与情况。</div>
          </el-tab-pane>
        </el-tabs>
      </div>
  
      <!-- 规则配置弹窗 -->
      <el-dialog v-model="showConfigDialog" :title="currentRule?.name" width="600px">
        <div style="display: flex; gap: 24px;">
          <div style="flex: 1;">
            <el-form :model="ruleConfigForm" label-width="90px">
              <template v-if="currentRule?.type === 'sign'">
                <el-form-item label="签到天数">
                  <el-input-number v-model="ruleConfigForm.days" :min="1" />
                </el-form-item>
              </template>
              <template v-else-if="currentRule?.type === 'invite'">
                <el-form-item label="邀请人数">
                  <el-input-number v-model="ruleConfigForm.inviteCount" :min="1" />
                </el-form-item>
              </template>
              <template v-else-if="currentRule?.type === 'share'">
                <el-form-item label="分享渠道">
                  <el-checkbox-group v-model="ruleConfigForm.channels">
                    <el-checkbox value="微信" />
                    <el-checkbox value="QQ" />
                    <el-checkbox value="微博" />
                  </el-checkbox-group>
                </el-form-item>
              </template>
              <template v-else-if="currentRule?.type === 'buy'">
                <el-form-item label="商品ID">
                  <el-input v-model="ruleConfigForm.productId" placeholder="请输入商品ID" />
                </el-form-item>
                <el-form-item label="最低金额">
                  <el-input-number v-model="ruleConfigForm.minAmount" :min="0" />
                </el-form-item>
              </template>
              <template v-else>
                <el-form-item label="参数A">
                  <el-input v-model="ruleConfigForm.paramA" />
                </el-form-item>
                <el-form-item label="参数B">
                  <el-input v-model="ruleConfigForm.paramB" />
                </el-form-item>
              </template>
              <!-- 奖励类型和奖励数量，所有规则都显示 -->
              <el-form-item label="奖励类型">
                <el-select v-model="ruleConfigForm.rewardType" placeholder="请选择">
                  <el-option label="积分" value="point" />
                  <el-option label="优惠券" value="coupon" />
                  <el-option label="现金" value="cash" />
                </el-select>
              </el-form-item>
              <el-form-item label="奖励数量">
                <el-input-number v-model="ruleConfigForm.rewardAmount" :min="1" />
              </el-form-item>
            </el-form>
          </div>
          <div style="flex: 1; background: #f7f8fa; padding: 12px; border-radius: 8px;">
            <div><strong>规则说明：</strong></div>
            <div>{{ currentRule?.desc }}</div>
            <div style="margin-top: 8px;"><strong>示例：</strong></div>
            <div>{{ currentRule?.example }}</div>
          </div>
        </div>
        <template #footer>
          <el-button type="default" @click="showConfigDialog = false">取消</el-button>
          <el-button type="primary" @click="saveRuleConfig">保存</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, watch, defineProps, defineEmits, computed, onMounted, reactive } from 'vue'
  import draggable from 'vuedraggable'
  
  const props = defineProps({
    modelValue: {
      type: Array,
      default: () => []
    }
  })
  const emit = defineEmits(['update:modelValue'])
  
  const LOCAL_KEY = 'taskEditorStep2'
  
  // 规则数据（可替换为接口数据）
  const allRules = [
    {
      id: 1,
      name: '每日签到',
      type: 'sign',
      typeLabel: '签到',
      desc: '用户每日登录签到获得奖励',
      scene: '日常活跃',
      complexity: 'simple',
      complexityLabel: '简单',
      example: '用户点击签到按钮即完成',
    },
    {
      id: 2,
      name: '邀请好友',
      type: 'invite',
      typeLabel: '邀请',
      desc: '邀请新用户注册并完成首单',
      scene: '拉新',
      complexity: 'medium',
      complexityLabel: '中等',
      example: '用户分享邀请码，好友注册并下单',
    },
    {
      id: 3,
      name: '分享活动',
      type: 'share',
      typeLabel: '分享',
      desc: '用户分享活动到社交平台',
      scene: '传播推广',
      complexity: 'simple',
      complexityLabel: '简单',
      example: '用户点击分享按钮，分享到微信/QQ',
    },
    {
      id: 4,
      name: '购买指定商品',
      type: 'buy',
      typeLabel: '购买',
      desc: '购买指定商品后获得奖励',
      scene: '促活转化',
      complexity: 'complex',
      complexityLabel: '复杂',
      example: '用户下单并支付指定商品',
    }
  ]
  
  const ruleTemplates = [
    { id: 1, name: '新手签到奖励', rules: [allRules[0]] },
    { id: 2, name: '拉新有礼', rules: [allRules[1]] }
  ]
  
  const recentRules = ref([allRules[0], allRules[2]])
  const activeTab = ref('all')
  const search = ref('')
  const filteredRules = computed(() => {
    let rules = allRules
    if (activeTab.value !== 'all') {
      rules = rules.filter(r => r.type === activeTab.value)
    }
    if (search.value) {
      rules = rules.filter(r => r.name.includes(search.value) || r.desc.includes(search.value))
    }
    return rules
  })
  
  const configuredRules = ref([])
  let initialized = false
  watch(() => props.modelValue, (val) => {
    if (!initialized && Array.isArray(val) && val.length) {
      configuredRules.value = [...val]
      initialized = true
    }
  }, { immediate: true })
  watch(configuredRules, (val) => {
    // 根据规则类型动态生成taskRule
    const taskRule = (Array.isArray(val) ? val : []).map(item => {
      const type = item.type || item.eventType || ''
      let value = ''
      if (type === 'sign') {
        value = String(item.config?.days ?? '')
      } else if (type === 'share') {
        value = (item.config?.channels || []).join(',')
      } else if (type === 'invite') {
        value = String(item.config?.inviteCount ?? '')
      } else if (type === 'buy') {
        value = String(item.config?.productId ?? '')
      } else {
        value = String(item.config?.paramA ?? '')
      }
      return {
        eventType: type,
        conditionTree: {
          executionFuncName: type,
          fieldName: type,
          operator: '',
          value
        },
        benefits: [
          {
            rewardType: (item.config?.rewardType || '').toUpperCase() || 'POINTS',
            rewardValue: String(item.config?.rewardAmount ?? '1')
          }
        ]
      }
    })
    localStorage.setItem('step2Data', JSON.stringify(taskRule))
  }, { deep: true })
  
  // 规则配置弹窗
  const showConfigDialog = ref(false)
  const currentRule = ref(null)
  const ruleConfigForm = ref({})
  let editingIndex = -1
  
  function openConfig(rule) {
    currentRule.value = rule
    // 根据类型初始化参数
    if (rule.type === 'sign') {
      Object.assign(ruleConfigForm.value, { days: 1 })
    } else if (rule.type === 'invite') {
      Object.assign(ruleConfigForm.value, { inviteCount: 1 })
    } else if (rule.type === 'share') {
      Object.assign(ruleConfigForm.value, { channels: [] })
    } else if (rule.type === 'buy') {
      Object.assign(ruleConfigForm.value, { productId: '', minAmount: 0 })
    } else {
      Object.assign(ruleConfigForm.value, { paramA: '', paramB: '' })
    }
    // 初始化奖励类型和数量，rewardType默认为point
    Object.assign(ruleConfigForm.value, { rewardType: 'point', rewardAmount: 1 })
    editingIndex = -1
    showConfigDialog.value = true
  }
  function saveRuleConfig() {
    // 奖励类型必选，默认为积分
    if (!ruleConfigForm.value.rewardType) {
      ruleConfigForm.value.rewardType = 'point'
    }
    let summary = ''
    if (currentRule.value.type === 'sign') {
      summary = `签到天数: ${ruleConfigForm.value.days}`
    } else if (currentRule.value.type === 'invite') {
      summary = `邀请人数: ${ruleConfigForm.value.inviteCount}`
    } else if (currentRule.value.type === 'share') {
      summary = `分享渠道: ${(ruleConfigForm.value.channels || []).join(',')}`
    } else if (currentRule.value.type === 'buy') {
      summary = `商品ID: ${ruleConfigForm.value.productId}, 最低金额: ${ruleConfigForm.value.minAmount}`
    } else {
      summary = `A:${ruleConfigForm.value.paramA}, B:${ruleConfigForm.value.paramB}`
    }
    summary += `，奖励: ${rewardTypeLabel(ruleConfigForm.value.rewardType)} x${ruleConfigForm.value.rewardAmount}`
    if (editingIndex >= 0) {
      configuredRules.value[editingIndex].configSummary = summary
      configuredRules.value[editingIndex].config = { ...ruleConfigForm.value }
    } else {
      configuredRules.value.push({
        ...currentRule.value,
        configSummary: summary,
        config: { ...ruleConfigForm.value }
      })
    }
    showConfigDialog.value = false
  }
  function editConfiguredRule(rule, idx) {
    currentRule.value = rule
    if (rule.type === 'sign') {
      Object.assign(ruleConfigForm.value, { days: rule.config?.days || 1 })
    } else if (rule.type === 'invite') {
      Object.assign(ruleConfigForm.value, { inviteCount: rule.config?.inviteCount || 1 })
    } else if (rule.type === 'share') {
      Object.assign(ruleConfigForm.value, { channels: rule.config?.channels || [] })
    } else if (rule.type === 'buy') {
      Object.assign(ruleConfigForm.value, { productId: rule.config?.productId || '', minAmount: rule.config?.minAmount || 0 })
    } else {
      Object.assign(ruleConfigForm.value, { paramA: rule.config?.paramA || '', paramB: rule.config?.paramB || '' })
    }
    // 奖励信息回填，rewardType默认为point
    Object.assign(ruleConfigForm.value, {
      rewardType: rule.config?.rewardType || 'point',
      rewardAmount: rule.config?.rewardAmount || 1
    })
    editingIndex = idx
    showConfigDialog.value = true
  }
  function removeConfiguredRule(idx) {
    configuredRules.value.splice(idx, 1)
  }
  function selectRule(rule) {
    openConfig(rule)
  }
  function filterRules() {
    // 由computed自动处理
  }
  function tagType(type) {
    return { sign: 'success', share: 'info', buy: 'warning', invite: 'primary' }[type] || ''
  }
  function complexType(complexity) {
    return { simple: 'success', medium: 'warning', complex: 'danger' }[complexity] || ''
  }
  function applyTemplate(tpl) {
    tpl.rules.forEach(rule => {
      configuredRules.value.push({
        ...rule,
        configSummary: 'A:默认, B:默认'
      })
    })
  }
  function rewardTypeLabel(type) {
    return { point: '积分', coupon: '优惠券', cash: '现金' }[type] || ''
  }

  const defaultRule = () => ({
    eventType: '',
    conditionTree: {
      executionFuncName: 'sign',
      fieldName: 'sign',
      operator: '',
      value: ''
    },
    benefits: [
      {
        rewardType: 'POINTS',
        rewardValue: '1'
      }
    ]
  })

  const form = reactive([
    defaultRule()
  ])

  onMounted(() => {
    const cache = localStorage.getItem('step2Data')
    if (cache) {
      const arr = JSON.parse(cache)
      if (Array.isArray(arr) && arr.length) {
        form.splice(0, form.length, ...arr)
      }
    }
  })

  function addRule() {
    form.push(defaultRule())
  }
  function removeRule(idx) {
    if (form.length > 1) form.splice(idx, 1)
  }
  </script>
  
  <style scoped>
  .step2-rule-config {
    display: flex;
    gap: 24px;
  }
  .config-area {
    flex: 3;
    background: #fff;
    padding: 24px;
    border-radius: 8px;
    min-width: 480px;
  }
  .help-area {
    flex: 1;
    background: #f5f7fa;
    padding: 24px;
    border-radius: 8px;
    min-width: 320px;
  }
  .rule-list {
    margin-top: 8px;
    margin-bottom: 8px;
  }
  .rule-card {
    margin-bottom: 16px;
  }
  .rule-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
  }
  .rule-desc {
    color: #888;
    margin-bottom: 8px;
  }
  .rule-meta {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 12px;
    color: #aaa;
  }
  .configured-rule {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
  }
  .mt16 {
    margin-top: 16px;
  }
  .mb16 {
    margin-bottom: 16px;
  }
  .tpl-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
  }
  </style>